/**
 * 
 */
package com.baijia.tianxiao.push.biz.channel.imp;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.baijia.tianxiao.push.biz.channel.StandardChannel;
import com.baijia.tianxiao.push.biz.channel.StandardChannelUtils;
import com.baijia.tianxiao.push.biz.channel.client.XiaomiSender;
import com.baijia.tianxiao.push.enums.ChannelTypeEnum;
import com.baijia.tianxiao.push.enums.DeviceTypeEnum;
import com.baijia.tianxiao.push.model.PushChannelConfig;
import com.baijia.tianxiao.push.result.BasePushResult;
import com.baijia.tianxiao.push.service.PushChannelConfigService;
import com.xiaomi.push.sdk.ErrorCode;
import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;



/**
 * @author leiruiqi
 *
 */

@Component
public class XiaomiPushChannelImpl implements StandardChannel{
	
	private static Logger logger = LoggerFactory.getLogger(XiaomiPushChannelImpl.class); 
	
	//BaiduPushClient pushClient;
	
	private Map<String,XiaomiSender> pushClientMap;
	
	@Resource
	private PushChannelConfigService pushChannelConfigService;
	
	public static final String TIMESTAMP_NORMAL = "yyyy-MM-dd HH:mm:ss";
	
	@PostConstruct
	public void init(){
		// 1. get apiKey and secretKey from developer console
		//String apiKey = "i30C5KZPV4eUNgsl15mQ4Gyh";
		//String secretKey = "zqNmmO7ywrADSdD7GeBwlFU6zpysvq4k";
		//PushKeyPair pair = new PushKeyPair(apiKey, secretKey);

		// 2. build a BaidupushClient object to access released interfaces
		//pushClient = new BaiduPushClient(pair,
		//		BaiduPushConstants.CHANNEL_REST_URL);

		// 3. register a YunLogHandler to get detail interacting information
		// in this request.
		pushClientMap = new HashMap<String,XiaomiSender>();
		
		// 放进统一的ChannelMap中
		
		StandardChannel.channelMap.put(ChannelTypeEnum.XIAOMI.name(), this);
	}
	
	private XiaomiSender getClient(DeviceTypeEnum deviceType,String appId,Integer developStatus){
		String key = StandardChannelUtils.buildClientKey(deviceType, appId, developStatus);
		XiaomiSender client =  pushClientMap.get(key);
		if(client == null){
			PushChannelConfig channelApp = pushChannelConfigService.getByChannelTypeAndIdByCache(ChannelTypeEnum.HUAWEI.name(),deviceType, appId,developStatus);
			if(channelApp != null){
				
				Sender sender = new Sender(channelApp.getAppSecret());
				client = new XiaomiSender();
				client.setSender(sender);
				pushClientMap.put(key, client);
			}
			
		}
		
		return client;
	}
	

	public BasePushResult sendPushMsg(JSONObject messageInfo, String appId,String deviceToken,String deviceType,Integer developStatus,Integer status) {
		DeviceTypeEnum typeEnum = DeviceTypeEnum.getByName(deviceType);
		if(typeEnum == null){
			return new BasePushResult(false, "deviceType not suport");	
		}
		
		XiaomiSender pushClient = getClient(typeEnum,appId,developStatus);
		
		
		if(pushClient == null){
			return new BasePushResult(false, "appId not config");	
		}
		
		Message message = null;
		
		if(typeEnum == DeviceTypeEnum.ANDROID){
			message = buildXiaomiAndroidMessagebody(messageInfo,pushClient.getChannelApp());
		}
		else if(typeEnum == DeviceTypeEnum.IOS){
			return new BasePushResult(false, "deviceType not suport");	
		}
		if(message == null){
			return new BasePushResult(false, "deviceType not suport");		
		}
		try {
			
	        //接口调用
			Result result = single_send(pushClient,message,deviceToken);
			logger.info("Server response: ", "MessageId: " + result.getMessageId()
            + " ErrorCode: " + result.getErrorCode().toString()
            + " Reason: " + result.getReason());
			ErrorCode  resultCode = result.getErrorCode();
	        
			if(resultCode == ErrorCode.Success){
				return new BasePushResult(true, null);
			}else{
				return new BasePushResult(false, resultCode.getName());
			}
			
		} catch (Exception e) {
			logger.error("",e);
			return new BasePushResult(false, "");
		}
		
	}
	
	
	private Message buildXiaomiAndroidMessagebody(JSONObject messageInfo,PushChannelConfig channelApp){
		//long currentTime = System.currentTimeMillis();
		String messagePayload = messageInfo.toJSONString();
	    String title = messageInfo.getString("title");
	    String description = messageInfo.getString("description");
	    // String alias = “testAlias”;    //alias非空白，不能包含逗号，长度小于128。
	     Message message = new Message.Builder()
	                .title(title)
	                .description(description).payload(messagePayload)
	                .restrictedPackageName(channelApp.getAppPackage())
	                .passThrough(1)  //消息使用透传方式
	                .notifyType(1)     // 使用默认提示音提示
	                .build();
        return message;
	}
	 /**
     * 单发消息
     * @param client
     * @throws NSPException
     */
    public Result single_send(XiaomiSender client,JSONObject messageInfo,String deviceToken)
        throws Exception
    {
    	Message message =  buildXiaomiAndroidMessagebody(messageInfo,client.getChannelApp());
      
    	Result result = client.getSender().send(message, deviceToken, 0);
    	     
        //打印响应
        return result;
    }
    
    /**
     * 单发消息
     * @param client
     * @throws NSPException
     */
    public Result single_send(XiaomiSender client,Message message,String deviceToken)
        throws Exception
    {
    	 
    	Result result = client.getSender().send(message, deviceToken, 0);
        
        return result;
    }

	@Override
	public void nofifyChannelConfigChange() {
		pushClientMap.clear();
		logger.info("xiaomi channel clear pushClientMap end");
	}
    
	
	
	
	/*public static void main(String[] args) {
		BaiduPushChannel channel = new BaiduPushChannel();
		channel.init();
		PushBindRecord record = new PushBindRecord();
		record.setUserId("123-123");
		record.setUserType("tx");
		record.setDeviceDomain(DeviceDomainEnum.MOBILE.name());
		record.setDeviceType(DeviceTypeEnum.ANDROID.name());
		channel.sendPushMsg(messageInfo, record., deviceType, status)
	}*/
}